#include "image_io.h"
#include "stb_image.h"
#include "stb_image_write.h"
#include <vector>
#include <cstring>

namespace vortex
{
    bool ImageIO::Read(const std::string& filePath, uint32_t channels)
    {
        int x, y, n;
        // the following function call flips the image
        // needs to be called before each stbi_load(...);
        stbi_set_flip_vertically_on_load(true);
        unsigned char* image_data = stbi_load(filePath.c_str(), &x, &y, &n, channels);

        if ( !image_data ) {
            fprintf( stderr, "ERROR: could not load %s\n", filePath.c_str() );
            return false;
        }
        // input image is not modified if 
        this->data = image_data;
        this->width = x;
        this->height = y;
        this->channels = n;
        return true;
    }

    bool ImageIO::Write(const std::string& filePath) const
    {
        uint32_t stride_in_bytes = width * channels * sizeof(uint8_t);
        stbi_write_png(filePath.c_str(), width, height, channels, data, stride_in_bytes);
        return true;
    }

    bool Imread(const std::string& filePath, ImageIO& image, uint32_t channels)
    {
        return image.Read(filePath, channels);
    }

    bool Imwrite(const std::string& filePath, const ImageIO& image)
    {
        return image.Write(filePath);
    }
}
